<?php

class Model extends Database {		

	public $properties = array();
	public $errors = array();
	
	function __construct($arr) {
		parent::__construct();
		$this->properties = $arr;
		//return new ucfirst($this->table_name)($arr);
	}
    
    public function validate_presence($field) {
        if( empty( $this->properties[$field] ) ) {
            $this->errors[$field] = ucfirst($field).': nu poate fi gol!';
        }
    }
    
    public function validate_numericality($field) {
        if( !empty($this->properties[$field]) && !is_numeric($this->properties[$field]) ) {
            $this->errors[$field] = ucfirst($field).': trebuie sa fie numeric!';
        }
    }
	
	public function validate() {
		return true;
	}

    public function find_by_condition( $table_name, $rest='' ){
		if( Database::$connection == null ) {
			$db = new Database();
		}
        $query="SELECT * FROM $table_name $rest";
		if( $db ) {
			$result=$db->query($query);
		} else {
			$result=$this->query($query);
		}
		//$klass = ucfirst($this->table_name);
		$klass = ucfirst($table_name);
		$ret = array();
        foreach( $result as $key => $value ) {
			$ret[]= new $klass($value);
		}
		return $ret;
    }
    
	public function find( $table_name, $arr = 'all' ){
		if( Database::$connection == null ) {
			$db = new Database();
		}
		if( $arr == 'all' ) {
	        return self::find_by_condition($table_name );
		} else {
            foreach($arr as $key => $value)
				$ins_fields[]=mysql_real_escape_string($key)."='".mysql_real_escape_string($value)."'";			
			$fields=implode(" and ",$ins_fields);
			//echo_r($fields);
	        return self::find_by_condition($table_name, ' WHERE '.$fields );

		}
        

	} 
    
    public function find_one( $table_name, $arr ) {
        $ret=self::find( $table_name, $arr );
        if( empty($ret) ) {
            return null;
        } else {
            return $ret[0];
        }
    }
	
	public function save() {
        if( $this->validate() ) {
			$this->save_without_validation();
			return true;
		} else {
			return false;
		}
	}
	
	public function save_without_validation() {
		$this->before_save();
        if( !empty($this->properties['id']) ) {
			return $this->update( $this->properties, $this->properties['id'] );
		} else {
			return $this->insert( $this->properties );
		}
	}
    
    public function before_save() {
    }
	
	public function delete(){
		if($this->properties['id']) {
			return parent::delete($this->properties['id']);
		} else {
			return 0;
		}
	}
	
}	